// cart.js
import to_page from '../../commons/pageaddress.js'
var requests = require('../../requests/api.js');
let filter = require('../../utils/filter.js');
import util from '../../utils/util.js'

let app = getApp()
Page(filter.identityFilter({

  /**
   * 页面的初始数据
   */
  data: {
    prompt: {
      hidden: !0,
      icon: '../../assets/coupons/default-coupons.png',
      title: '暂无商品',
    },
    goodsList: [

    ],
    //商品分组列表
    shoppingCartGroupVos: [

    ],
    //分组信息
    promotionGroupVos: {

    },
    totalAmount: 0,
    allSelect: true,
    noSelect: false,


  },


  onLoad: function(options) {
  
    new app.WeToast();

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
  
    if (app.isNeedLogin()) {
      this.getUserInfo()
      return
    }
    this.request_cartlist()

  },

  getUserInfo() {

    var that = this
    //调用应用实例的方法获取全局数据
    app.login({
      //success回调
      success: function(endUser) {
        //更新数据

        that.request_cartlist()

      },
      fail: null,
      authFail: () => {
        wx.switchTab({
          url: '../../pages/home/home',
        })
      },
    })
  },

  //NET
  //购物车列表
  request_cartlist: function() {
    const that = this
    var params = {};
    requests.get_cart(params, (res) => {
      this.validatePromotion(res.data);
      this.setData({
        goodsList: res.data.shoppingCartGroupVos,
        promotionGroupVos: res.data.promotionGroupVos,
        totalAmount: res.data.totalAmount,
        allSelect: res.data.isAllSelect,
        noSelect: res.data.isNoneSelect,
        'prompt.hidden': res.data.shoppingCartGroupVos.length
      })

    }, (data) => {

      this.setData({
        'prompt.hidden': 0,
        goodsList: []
      })
      if (util.alertNetworkError(data)) {
        if (data.resCode == 10000) {

        } else {
          that.wetoast.toast({
            title: data.resMsg,
          })
        }
      }

    }, () => {

    });
  },
  //计算是否满足打包购条件
  validatePromotion: function(data) {
    var cartList = data.shoppingCartGroupVos;
    var group = data.promotionGroupVos;
    for (var i = 0; i < cartList.length; i++) {
      if (cartList[i].groupKey != "default") {
        if (group[cartList[i].groupKey].promotionType == 2) {
          var cartItems = cartList[i].shoppingCartItemVos
          var productQty = 0
          for (var j = 0; j < cartItems.length; j++) {
            productQty += cartItems[j].productQty
          }
          if (productQty < group[cartList[i].groupKey].promotionRuleVos[0].promotionThreshold) {
            group[cartList[i].groupKey].isFit = false

          } else {
            group[cartList[i].groupKey].isFit = true

          }
        }
      }

    }
  },
  //删除购物车产品
  request_deletecart: function(shoppingCartId) {
    const that = this
    var params = {
      ids: [shoppingCartId]
    };
    requests.delete_cart(params, (res) => {
      that.request_cartlist()

    }, (data) => {
      if (util.alertNetworkError(data)) {
        that.wetoast.toast({
          title: data.resMsg,
        })
      }
    }, () => {

    });
  },

  //修改购物车产品数量
  request_putcart: function(productInfo, index) {
    const that = this
    var list = that.data.goodsList;

    var params = {
      productId: productInfo.shoppingCartId,
      productQty: productInfo.productQty
    };
    requests.put_cart(params, (res) => {
      that.request_cartlist()

    }, (data) => {
      if (util.alertNetworkError(data)) {
        that.wetoast.toast({
          title: data.resMsg,
        })
      }
    }, () => {

    });
  },

  //将购物车中的产品设置为已选中(未选中)
  put_cartSelected: function(list, shoppingCartIds, isSelected) {
    const that = this
    var params = {
      shoppingCartIds: shoppingCartIds,
      isSelected: isSelected
    };
    requests.put_cartSelected(params, (res) => {
      that.request_cartlist()

    }, (data) => {
      if (util.alertNetworkError(data)) {
        that.wetoast.toast({
          title: data.resMsg,
        })
      }
    }, () => {

    });
  },
  //MARK: -- private themod


  /**
   * 选中单个商品
   */
  selectTap: function(e) {
    const that = this;
    var shoppingCartIds = [];
    var section = e.currentTarget.dataset.section;
    var index = e.currentTarget.dataset.index;
    var list = that.data.goodsList;
    if (index !== "" && index != null) {
      let isSelected = !list[parseInt(section)].shoppingCartItemVos[parseInt(index)].isSelected;
      list[parseInt(section)].shoppingCartItemVos[parseInt(index)].isSelected = isSelected;
      shoppingCartIds = [list[parseInt(section)].shoppingCartItemVos[parseInt(index)].shoppingCartId];
      wx.showLoading({
        title: '',
      });
      that.put_cartSelected(list, shoppingCartIds, isSelected);

    };

  },


  /**
   * 全选按钮
   */
  bindAllSelect: function() {
    const that = this;
    var shoppingCartIds = [];

    var currentAllSelect = that.data.allSelect;
    var list = that.data.goodsList;
    if (currentAllSelect) {
      for (var i = 0; i < list.length; i++) {
        var curItem = list[i].shoppingCartItemVos;
        for (var j = 0; j < curItem.length; j++) {
          var productInfo = curItem[j];
          productInfo.isSelected = false
          shoppingCartIds.push(productInfo.shoppingCartId);
        }

      }
    } else {
      for (var i = 0; i < list.length; i++) {
        var curItem = list[i].shoppingCartItemVos;
        for (var j = 0; j < curItem.length; j++) {
          var productInfo = curItem[j];
          if (productInfo.productStatus == 1 && productInfo.productStock > 0) {
            productInfo.isSelected = true;
            shoppingCartIds.push(productInfo.shoppingCartId);
          }
        }

      }
    };
    wx.showLoading({
      title: '',
    });
    that.put_cartSelected(list, shoppingCartIds, !currentAllSelect);

  },

  /**
   * 商品减数量
   */
  jian_click: function(e) {
    var section = e.currentTarget.dataset.section;
    var index = e.currentTarget.dataset.index;
    const that = this;

    var list = that.data.goodsList;
    if (index !== "" && index != null) {
      var productInfo = list[parseInt(section)].shoppingCartItemVos[parseInt(index)];
      if (productInfo.productQty > 1) {
        productInfo.productQty--;
        wx.showLoading({
          title: '',
        })
        that.request_putcart(productInfo, parseInt(index))

      }
    }
  },

  /**
   * 商品加数量
   */
  jia_click: function(e) {
    var section = e.currentTarget.dataset.section;
    var index = e.currentTarget.dataset.index;
    const that = this;

    var list = that.data.goodsList;
    if (index !== "" && index != null) {
      var productInfo = list[parseInt(section)].shoppingCartItemVos[parseInt(index)];

      if (productInfo.productQty < productInfo.productStock) {
        productInfo.productQty++;
        wx.showLoading({
          title: '',
        })
        that.request_putcart(productInfo, parseInt(index))
      }
    };


  },

  /**
   * 删除按钮
   */
  delete_click: function(e) {
    const that = this;
    var list = that.data.goodsList;
    var section = e.currentTarget.dataset.section;
    var index = e.currentTarget.dataset.index;
    let productTitle = list[parseInt(section)].shoppingCartItemVos[parseInt(index)].productTitle;
    wx.showModal({
      title: '提示',
      content: '确定要删除"' + productTitle + '"?',
      success: function(res) {
        if (res.confirm) {

          that.request_deletecart(list[parseInt(section)].shoppingCartItemVos[parseInt(index)].shoppingCartId)


        } else if (res.cancel) {

        }
      }
    })
  },

  /**
   * 当页面滑动到底部时触发的方法,删掉这个方法后控制台会报事件警告
   */
  onReachBottom: function() {},

  /**
   * 去结算
   */
  toEditOrder: function() {
    const that = this
    if (that.data.noSelect) {
      that.wetoast.toast({
        title: '您还没有选中商品',
      })
      return
    }

    //检验结算商品信息
    var list; // = that.data.goodsList;
    for (var x = 0; x < that.data.goodsList.length; x++) {
      list = that.data.goodsList[x].shoppingCartItemVos

      for (var i = 0; i < list.length; i++) {
        var productInfo = list[i];
        if (productInfo.isSelected) {
          var skuid = productInfo.productId; // 这个是检查是否有相同的id去结算
        }
        var showTimes = 0;
        if (productInfo.isSelected) {
          if (productInfo.productStatus == -1) {
            that.wetoast.toast({
              title: '您购买的商品"' + productInfo.productTitle + '"已失效',
            })
            return
          }
          if (productInfo.productStatus == 2) {
            that.wetoast.toast({
              title: '您购买的商品"' + productInfo.productTitle + '"已下架',
            })
            return
          }
          if (productInfo.productStatus == 1 && productInfo.productStock == 0) {
            that.wetoast.toast({
              title: '您购买的商品"' + productInfo.productTitle + '"已售罄',
            })
            return
          }
          if (productInfo.limitQty > 0) {
            if (productInfo.productQty > productInfo.limitQty) {
              that.wetoast.toast({
                title: '"' + productInfo.productTitle + '"每人限购' + productInfo.limitQty + '件，请修改',
              })
              return
            }
          }
          for (var j = 0; j < list.length; j++) {
            if (skuid == list[j].productId && list[j].isSelected) {
              showTimes++;
              if (showTimes > 1) {
                that.wetoast.toast({
                  title: '活动中的商品请与原商品分开购买',
                })
                return
              }
            }
          }
        }
      }
    }

    var url = to_page.o + to_page.goEditOrder;
    to_page.to(url)

  },

  goods_detailClick: function(e) {
    var id = e.currentTarget.dataset.productid;
    wx.navigateTo({
      url: '../product/productDetail?productId=' + id,
    })
  },
  promotionTap: function(e) {
    //不知道为什么转过来是小写的
    var promotionType = e.currentTarget.dataset.promotiontype;
    var promotionId = e.currentTarget.dataset.promotionid;
    // 如果是打包购的话可以跳转到列表页
    if (promotionType == 2) {
      console.log("跳转到促销页面")
      wx.navigateTo({
        url: '../promotion/promotion?promotionId=' + promotionId,
      })
    }
  }
}))